/// <summary>
// DBLinq.MySqlProviders - .NET Providers for MySql using the framework DBLinq under MIT license, author Jiri George Moudry
// http://linq.to/db
// and the CodeFx.MySqlProviders under GNU licence, author Laurent Morisseau
// http://www.codeplex.com/CodeFxMySqlProvider
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Laurent Morisseau
/// </summary>
/// <author><a href="mailto:laurent.morisseau@gmail.com">Laurent Morisseau</a></author>


namespace DBLinq.MySqlProviders
{
	using System;
	using System.Web;
	using System.ComponentModel;
	using System.Collections.Specialized;
	using System.Linq;

	internal static partial class AspNetUsersDTO
	{
		internal static void Insert( AspNetUser user )
		{
			using ( aspnetcontext context = new aspnetcontext ( ConnectionString.Current.CurrentString ) )
			{
				context.AspNetUsers.Add ( user );
				context.SubmitChanges ();
			}
		}

		internal static void Delete( uint UserID )
		{
			using ( aspnetcontext context = new aspnetcontext ( ConnectionString.Current.CurrentString ) )
			{
                var q = context.AspNetUsers.Where<AspNetUser>(p => p.UserId == UserID).ToList();
                if (q.Count > 0)
                {
                    context.AspNetUsers.Remove(q.First < AspNetUser>());
                    context.SubmitChanges();
                }
			}
		}

		internal static uint GetLastId( AspNetUser user )
		{
			using ( aspnetcontext context = new aspnetcontext ( ConnectionString.Current.CurrentString ) )
			{
                string name = user.UserName;
                uint appid = user.ApplicationId;
                AspNetUser lastuser = context.AspNetUsers.Where(p => p.UserName == name && p.ApplicationId == appid).ToList<AspNetUser>().LastOrDefault<AspNetUser>();
                if (lastuser != null)
                    return lastuser.UserId;
                else
                    return 0;
			}
		}

		internal static AspNetUser Select( uint userid )
		{
			using ( aspnetcontext context = new aspnetcontext ( ConnectionString.Current.CurrentString ) )
			{
				return context.AspNetUsers.First<AspNetUser> ( p => p.UserId == userid );
			}
		}

		internal static StringCollection UsersInRoles_FindUsersInRole( uint ApplicationId, uint RoleId, string UserNameToMatch )
		{

			StringCollection al = null;
			using ( aspnetcontext context = new aspnetcontext ( ConnectionString.Current.CurrentString ) )
			{
				var users = from u in context.AspNetUsers
					  join ur in context.AspNetUsersInRoles on u.UserId equals ur.UserId
					  where u.ApplicationId == ApplicationId
					  && u.UserName == UserNameToMatch
					  orderby u.UserName
					  select u.UserName;
				if ( users != null )
				{
					al = new StringCollection ();
					foreach ( var user in users )
					{
						al.Add ( user );
					}
				}
			} return al;
		}

		internal static void Update_LastActivityDateWithPersistance( uint userid, string username )
		{
			string Key = string.Concat ( "AspNetUsers_", username );
			AspNetUser dataobject = HttpContext.Current.Items[ Key ] as AspNetUser;
			if ( dataobject != null )
			{
				dataobject.LastActivityDate = DateTime.UtcNow;
				HttpContext.Current.Items[ Key ] = dataobject;
			}
			Update_LastActivityDate ( userid );
		}

		private static void Update_LastActivityDate( uint userid )
		{
			using ( aspnetcontext context = new aspnetcontext ( ConnectionString.Current.CurrentString ) )
			{
				AspNetUser user = context.AspNetUsers.Single<AspNetUser> ( p => p.UserId == userid );
				user.LastActivityDate = DateTime.UtcNow;
				context.SubmitChanges ();
			}
		}
 
		[DataObjectMethodAttribute ( DataObjectMethodType.Select, false )]
		internal static AspNetUser SelectByFk_ApplicationId_UserNameWithPersistance( uint ApplicationId, string UserName )
		{
			string Key = string.Concat ( "AspNetUsers_", UserName );
            bool persistance = HttpContext.Current != null && HttpContext.Current.Items != null;
            AspNetUser dataobject = null;
            if (persistance)
			    dataobject = HttpContext.Current.Items[ Key ] as AspNetUser;
			if ( dataobject == null )
			{
				using ( aspnetcontext context = new aspnetcontext ( ConnectionString.Current.CurrentString ) )
				{
                    var user = context.AspNetUsers.Where<AspNetUser>(p => p.ApplicationId == ApplicationId && p.UserName == UserName).ToList();
                    if (user.Count>0)
					    dataobject = user.First();
				}
				if ( dataobject != null  && persistance)
					HttpContext.Current.Items[ Key ] = dataobject;
			}
			return dataobject;

		}

		
		internal static StringCollection UsersInRoles_GetUsersInRoles( uint ApplicationId, uint RoleId )
		{

			StringCollection al = null;
			using ( aspnetcontext context = new aspnetcontext ( ConnectionString.Current.CurrentString ) )
			{
				var users= from u in context.AspNetUsers 
					     join ur in context.AspNetUsersInRoles on u.UserId equals ur.UserId
					     where
						     ur.RoleId == RoleId && u.ApplicationId == ApplicationId
					     orderby u.UserName
					     select u.UserName;
				if ( users != null )
				{
					al = new StringCollection ();
					foreach ( var user in users )
					{
						al.Add ( user);
					}
				}
			}
			return al;
		}

		internal static uint GetUserId( string _UserName, uint _ApplicationId )
		{
			string key = string.Concat ( "AspNetUsers_Id_", _UserName );
            bool persistance = HttpContext.Current != null && HttpContext.Current.Items != null;
            if (persistance && HttpContext.Current.Items[key] != null)
				return ( uint ) HttpContext.Current.Items[ key ];
			else
			{
				using ( aspnetcontext context = new aspnetcontext ( ConnectionString.Current.CurrentString ) )
				{
                    uint userid = context.AspNetUsers.Where(u => u.UserName == _UserName && u.ApplicationId == _ApplicationId).ToList<AspNetUser>().First < AspNetUser>().UserId;
                    if (persistance)
					    HttpContext.Current.Items[ key ] = userid;
					return userid;
				}
			}
		}
	}
}